//
//  UIImageView+Extension.m
//  BSBuDeJie
//
//  Created by monkey on 2018/12/30.
//  Copyright © 2018 itcast. All rights reserved.
//

#import <SDWebImage/UIImageView+WebCache.h>
#import <AFNetworking/AFNetworkReachabilityManager.h>

#import "UIImageView+Extension.h"

@implementation UIImageView (Extension)

- (void)xg_setImageWithURLString:(NSString *)urlString placeHolder:(UIImage *)placeHolder
{
    [self xg_setImageWithURLString:urlString placeHolder:placeHolder completion:nil];
}

- (void)xg_setImageWithURLString:(NSString *)urlString placeHolder:(UIImage *)placeHolder completion:(void (^)(NSError *, UIImage *))completion
{
    SDImageCache *imageCache = [SDImageCache sharedImageCache];
    if ([imageCache imageFromCacheForKey:urlString]) {
        // 本地有缓存
        [self sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeHolder options:SDWebImageRefreshCached | SDWebImageRetryFailed completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (completion) {
                completion(error,image);
            }
        }];
    } else if ([AFNetworkReachabilityManager sharedManager].reachable) {
        // 网络可用 进行下载
        [self sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:placeHolder options:SDWebImageRefreshCached | SDWebImageRetryFailed completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            if (completion) {
                completion(error,image);
            }
        }];
    } else {
        // 网络不可用 显示占位图
        self.image = placeHolder;
        if (completion) {
            completion([NSError errorWithDomain:@"error" code:-999 userInfo:@{@"reason" : @"网络不可用"}],nil);
        }
    }
}

@end
